// 路由配置
import {createRouter, createWebHistory} from "vue-router";

// 导入进度条组件
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false });

// 定义路由信息
const routes = [{
    path: "/login",
    name: "login",
    component: () => import("../pages/Login.vue")
}, {
    path: "/index",
    name: "index",
    redirect: '/index/welcome',
    component: () => import("../pages/Index.vue"),
    children: [{
        path: "welcome",
        name: "welcome",
        component: () => import("../pages/Welcome.vue")
    }, {
        path: "/userlist",
        name: "userlist",
        component: () => import("../pages/user/Userlist.vue")
    }, {
        path: "/useradd",
        name: "useradd",
        component: () => import("../pages/user/Useradd.vue")
    }, {
        path: "payList",
        name: "paylist",
        component: () => import("../pages/pay/PayList.vue")
    }]
}, {
    path: "/",
    redirect: "/index"
}];

// 定义路由对象
const router = createRouter({
    history: createWebHistory(),
    routes
});

// 配置路由的全局前置导航守卫
router.beforeEach((to, from, next) => {
    console.log("前置");
    // 开启滚动条
    NProgress.start();
    // 访问的非登录组件以外的组件，需要判断sessionStorage中有token
    let token = sessionStorage.getItem("token");
    if (to.name == 'login') {
        // 跳转的是登陆组件，可以直接跳转
        next();
    } else {
        if (!token) {
            // 没有登录
            next({
                name: "login"
            });
        } else {
            // 登录
            next();
        }
    }
});

// 配置路由的全局后置钩子
router.afterEach((to, from) => {
    console.log("后置");
    // 结束滚动条
    NProgress.done();
});

// 对外导出路由模块
export default router;